//
//  SpeechViewController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/6.
//
//  文字语音合成,文字播报
import UIKit
import AVFoundation

class SpeechViewController: UIViewController, AVSpeechSynthesizerDelegate {
    
    // MARK: - UI 组件
    let textView = UITextView()
    let playButton = UIButton(type: .system)
    let pauseButton = UIButton(type: .system)
    let continueButton = UIButton(type: .system)
    let stopButton = UIButton(type: .system)
    let statusLabel = UILabel()
    
    // 创建语音合成器
    let synthesizer = AVSpeechSynthesizer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupSpeechSynthesizer()
    }
    
    // MARK: - 界面设置
    private func setupUI() {
        view.backgroundColor = .white
        
        // 文本输入框
        textView.text = """
Парад в День Победы в отечественной войне в россии () — большой парад в честь победы в отечественной войне. В 22 часа по местному времени 29 апреля 2025 года в москве состоялась первая репетиция военного парада в честь 80 - й годовщины победы в отечественной войне.
"""
        textView.text = """
        俄罗斯卫国战争胜利日阅兵，是为纪念卫国战争胜利举行的盛大阅兵仪式。
        当地时间2025年4月29日22点，俄罗斯纪念卫国战争胜利80周年阅兵式在莫斯科举行首次彩排彩排正式开始。
        """
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.layer.borderWidth = 1
        textView.layer.borderColor = UIColor.lightGray.cgColor
        textView.layer.cornerRadius = 5
        view.addSubview(textView)
        
        // 播放按钮
        playButton.setTitle("播放", for: .normal)
        playButton.addTarget(self, action: #selector(playSpeech), for: .touchUpInside)
        view.addSubview(playButton)
        
        // 暂停按钮
        pauseButton.setTitle("暂停", for: .normal)
        pauseButton.addTarget(self, action: #selector(pauseSpeech), for: .touchUpInside)
        view.addSubview(pauseButton)
        
        // 继续按钮
        continueButton.setTitle("继续", for: .normal)
        continueButton.addTarget(self, action: #selector(continueSpeech), for: .touchUpInside)
        view.addSubview(continueButton)
        
        // 停止按钮
        stopButton.setTitle("停止", for: .normal)
        stopButton.addTarget(self, action: #selector(stopSpeech), for: .touchUpInside)
        view.addSubview(stopButton)
        
        // 状态标签
        statusLabel.text = "准备就绪"
        statusLabel.textAlignment = .center
        view.addSubview(statusLabel)
        
        // 布局设置
        textView.translatesAutoresizingMaskIntoConstraints = false
        playButton.translatesAutoresizingMaskIntoConstraints = false
        pauseButton.translatesAutoresizingMaskIntoConstraints = false
        continueButton.translatesAutoresizingMaskIntoConstraints = false
        stopButton.translatesAutoresizingMaskIntoConstraints = false
        statusLabel.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            textView.heightAnchor.constraint(equalToConstant: 150),
            
            playButton.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 20),
            playButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            
            pauseButton.topAnchor.constraint(equalTo: playButton.topAnchor),
            pauseButton.leadingAnchor.constraint(equalTo: playButton.trailingAnchor, constant: 20),
            
            continueButton.topAnchor.constraint(equalTo: playButton.topAnchor),
            continueButton.leadingAnchor.constraint(equalTo: pauseButton.trailingAnchor, constant: 20),
            
            stopButton.topAnchor.constraint(equalTo: playButton.topAnchor),
            stopButton.leadingAnchor.constraint(equalTo: continueButton.trailingAnchor, constant: 20),
            
            statusLabel.topAnchor.constraint(equalTo: playButton.bottomAnchor, constant: 20),
            statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)
        ])
    }
    
    // MARK: - 语音合成器设置
    private func setupSpeechSynthesizer() {
        synthesizer.delegate = self
    }
    
    // MARK: - 按钮动作
    
    @objc private func playSpeech() {
        guard !textView.text.isEmpty else {
            statusLabel.text = "请输入要朗读的文本"
            return
        }
        
        // 创建要朗读的文本
        let utterance = AVSpeechUtterance(string: textView.text)
        
        // 配置语音参数
        utterance.voice = AVSpeechSynthesisVoice(language: "zh-CN") // 中文语音
        // utterance.voice = AVSpeechSynthesisVoice(language: "ru-RU") // 俄语语音
        // 设置语速 (0.0-1.0) 默认: 0.5
        utterance.rate = AVSpeechUtteranceDefaultSpeechRate
        // 设置音调 (0.5-2.0)
        utterance.pitchMultiplier = 1.0
        // 设置音量 (0.0-1.0)
        utterance.volume = 1.0 // 最大音量
        // 朗读前的延迟
        utterance.preUtteranceDelay = 0.0
        // 朗读后的延迟
        utterance.postUtteranceDelay = 0.0
        
        // 开始朗读
        synthesizer.speak(utterance)
        statusLabel.text = "正在朗读..."
    }
    
    @objc private func pauseSpeech() {
        if synthesizer.isSpeaking {
            synthesizer.pauseSpeaking(at: .word) // 当前单词结束后暂停
            statusLabel.text = "已暂停"
        }
    }
    
    @objc private func continueSpeech() {
        if synthesizer.isPaused {
            synthesizer.continueSpeaking()
            statusLabel.text = "继续朗读..."
        }
    }
    
    @objc private func stopSpeech() {
        if synthesizer.isSpeaking || synthesizer.isPaused {
            // 停止
            // 立即停止
            synthesizer.stopSpeaking(at: .immediate)
            // 当前单词结束后停止
            // synthesizer.stopSpeaking(at: .word)
            statusLabel.text = "已停止"
        }
    }
    
    // MARK: - AVSpeechSynthesizerDelegate 方法
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
        print("开始朗读: \(utterance.speechString)")
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        statusLabel.text = "朗读完成"
        print("完成朗读: \(utterance.speechString)")
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {
        print("朗读暂停")
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {
        print("朗读继续")
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
        statusLabel.text = "朗读取消"
        print("朗读取消")
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
        let progress = Float(characterRange.location) / Float(utterance.speechString.count)
        print("朗读进度: \(progress * 100)%")
    }
}
